package com.helwen.tools.zhijiang;

import org.apache.poi.xwpf.usermodel.*;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 读取word，  修改格式后，写入另一个word
 *
 * @author Christmas_G
 *
 */
public class ExcelReadandWrite {

    private Map<String,String> fieldMap=new HashMap<>();
    @Test
    public void readWord() throws FileNotFoundException, IOException {
        XWPFDocument document = new XWPFDocument(new FileInputStream("C:\\develop\\docs\\枝江\\公卫\\【业务篇】数据采集接口说明(健康体检职业危害因素).doc"));

        try {
            getWordFieldMap();
            // 获取word中的所有段落与表格
            List<IBodyElement> elements = document.getBodyElements();
            List<XWPFTable> tables = document.getTables();
            String protocol="";
            int tableCount=0;
            Map<String,Object> map=new HashMap<>();
            for (XWPFTable element : tables) {
                /*// 段落
                if (element instanceof XWPFParagraph) {
                    protocol= getTableCellText((XWPFParagraph) element);
                }
                // 表格
                else if (element instanceof XWPFTable) {
                    getTabelText((XWPFTable) element,protocol);
                }*/
                if (element instanceof XWPFTable) {
                    tableCount++;
                    if(tableCount<=3){
                        if(tableCount==2){
                            String tname=getTabelTextName((XWPFTable) element,2);
                            map.put("tableName",tname);
                        }else if(tableCount==3){
                            List<PublicHealthEntity> list=getTabelText((XWPFTable) element);
                            map.put("data",list);
                        }

                    }

                }
            }
            createWord(map);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            document.close();
        }
    }



    private String getTableCellText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            System.out.println("按了回车（新段落）");
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        //System.out.println(runText);

        return runText.toString();
    }

    /**
     * 获取表格内容,取第二行数据表的名称
     *
     * @param table
     */
    private String getTabelTextName(XWPFTable table,int tableCount) throws Exception{
        List<XWPFTableRow> rows = table.getRows();
        int x=0;
        for (XWPFTableRow row : rows) {
            if(x==0){
                x++;
                continue;
            }
            List<XWPFTableCell> cells = row.getTableCells();
            if(tableCount==2){
                //获取注释
                List<XWPFParagraph> explans = cells.get(1).getParagraphs();//取第4个单元格中的值。
                String name=getTableCellText(explans.get(0));//
                return name;
            }

        }
        return null;

    }


    /***
    *
    * 取得所有的数据
     * @param table
    *@author:Dell
    *@date:2021/6/22 10:54
    *@return:
 * @return java.util.List<com.helwen.tools.zhijiang.PublicHealthEntity>
    */
    private List<PublicHealthEntity> getTabelText(XWPFTable table) throws Exception{
        List<XWPFTableRow> rows = table.getRows();
        int x=0;
        List<PublicHealthEntity> list=new ArrayList<>();
        for (XWPFTableRow row : rows) {
            if(x==0){
                x++;
                continue;
            }
            List<XWPFTableCell> cells = row.getTableCells();
            /*int i=0;
            for (XWPFTableCell cell : cells) {
                // 简单获取内容（简单方式是不能获取字体对齐方式的）
                // System.out.println(cell.getText());
                // 一个单元格可以理解为一个word文档，单元格里也可以加段落与表格
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    getTableCellText(paragraph);
                }
            }*/
            PublicHealthEntity entity=new PublicHealthEntity();
            //获取路径
            List<XWPFParagraph> paragraphs = cells.get(0).getParagraphs();//取第一个单元格中的值，
            String name=getTableCellText(paragraphs.get(0));//
            //获取注释
            List<XWPFParagraph> explans = cells.get(1).getParagraphs();//取第二个单元格中的值。
            String type=getTableCellText(explans.get(0));//
            //获取路径
            List<XWPFParagraph> isNeed = cells.get(2).getParagraphs();//取第三个单元格中的值
            String need=getTableCellText(isNeed.get(0));//
            if(need==null || "".equals(need)){
                need="N";
            }
            //获取注释
            List<XWPFParagraph> description = cells.get(3).getParagraphs();//取第四个单元格中的值。
            String desc=getTableCellText(description.get(0));//
            //获取路径
            List<XWPFParagraph> contentdy = cells.get(4).getParagraphs();//取第五个单元格中的值
            String content=getTableCellText(contentdy.get(0));//
            //获取注释
            List<XWPFParagraph> restriction = cells.get(5).getParagraphs();//取第六个单元格中的值。
            String restrict=getTableCellText(restriction.get(0));//

            entity.setName(name);
            entity.setType(type);
            entity.setNeed(need);
            entity.setContent(content);
            entity.setDesc(desc);
            entity.setRestrict(restrict);
            list.add(entity);
        }
        return list;

    }


    private String getSpecificationWord(String word){
        if(word.length()>1){
            return word.substring(0, 1).toUpperCase()+word.substring(1);
        }else {
            return word;
        }
    }

    private void createWord(Map<String,Object> map) throws Exception{
        //Blank Document
        XWPFDocument document= new XWPFDocument();

        //Write the Document in file system
        FileOutputStream out = new FileOutputStream(new File("create_table.docx"));

        //添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun titleParagraphRun = titleParagraph.createRun();
        String tableName=(String) map.get("tableName");
        titleParagraphRun.setText(tableName);//标题
        titleParagraphRun.setColor("000000");
        titleParagraphRun.setFontSize(20);


        //段落
        XWPFParagraph firstParagraph = document.createParagraph();
        XWPFRun run = firstParagraph.createRun();
        run.setText("对应数据库表"+tableName);
        run.setFontSize(16);
        //设置段落背景颜色
        CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
        cTShd.setVal(STShd.CLEAR);
        cTShd.setFill("97FFFF");

        //工作经历表格
        XWPFTable ComTable = document.createTable();

        //列宽自动分割
        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(9072));

        List<PublicHealthEntity> list=(List<PublicHealthEntity>)map.get("data");
        //表格第一行
        XWPFTableRow comTableRowOne = ComTable.getRow(0);
        comTableRowOne.getCell(0).setText("字段");
        comTableRowOne.addNewTableCell().setText("字段名称");
        comTableRowOne.addNewTableCell().setText("字段说明");
        comTableRowOne.addNewTableCell().setText("类型");
        comTableRowOne.addNewTableCell().setText("是否必填");
        comTableRowOne.addNewTableCell().setText("值域标准");
        comTableRowOne.addNewTableCell().setText("宜昌平台对应字段");
        comTableRowOne.addNewTableCell().setText("CDA文档XML路径");
        for(PublicHealthEntity entity:list){
            //表格第二行
            XWPFTableRow comTableRowTwo = ComTable.createRow();
            String field=fieldMap.get(entity.getDesc());
            if(field!=null){
                comTableRowTwo.getCell(0).setText(field);
            }else {
                comTableRowTwo.getCell(0).setText("");
            }
            comTableRowTwo.getCell(1).setText(entity.getDesc());
            comTableRowTwo.getCell(2).setText(entity.getContent());
            comTableRowTwo.getCell(3).setText(entity.getType());
            comTableRowTwo.getCell(4).setText(entity.getNeed());
            comTableRowTwo.getCell(5).setText(entity.getRestrict());
            comTableRowTwo.getCell(6).setText(entity.getName());
            comTableRowTwo.getCell(7).setText("");

        }
        document.write(out);
        out.close();
        System.out.println("create_table document written success.");


    }



    private Map<String,String> getWordFieldMap() throws Exception{

        XWPFDocument document = new XWPFDocument(new FileInputStream("C:\\develop\\docs\\枝江\\fielddemo.docx"));
        try {
            // 获取word中的所有段落与表格
            //List<IBodyElement> elements = document.getBodyElements();
            List<XWPFTable> tables = document.getTables();

            for (XWPFTable table : tables) {
                List<XWPFTableRow> rows = table.getRows();
                int x=0;
                for (XWPFTableRow row : rows) {
                    if(x==0){
                        x++;
                        continue;
                    }
                    List<XWPFTableCell> cells = row.getTableCells();
                    //获取注释
                    List<XWPFParagraph> fieldmean = cells.get(1).getParagraphs();//取第4个单元格中的值。
                    String name=getTableCellText(fieldmean.get(0));//

                    List<XWPFParagraph> field = cells.get(0).getParagraphs();//取第4个单元格中的值。
                    String fi=getTableCellText(field.get(0));//

                    if(name!=null && !"".equals(name)){
                        fieldMap.put(name,fi);
                    }

                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            document.close();
        }
        return fieldMap;
    }

}
